package com.tn.openrpc.jms.acceptance.performance;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.tn.openrpc.RemoteMethod;
import com.tn.openrpc.RemoteMethodException;

/**
 * The client side of the performance acceptance test, which sends continues messages to the <i>echo service</i> logging
 * the response times.
 */
public class Client
{
  private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

  private static final String APPLICATION_CONTEXT_FILE = "performance/client.xml";

  public static boolean running = true;

  /**
   * Program entry point.
   */
  public static void main(String[] args)
  {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
      APPLICATION_CONTEXT_FILE
    );
    applicationContext.start();

    RemoteMethod remoteMethod = applicationContext.getBean(RemoteMethod.class);

    while (running)
    {
      long start = System.currentTimeMillis();

      try
      {
        String result = (String) remoteMethod.invoke(Long.toString(start));
        LOGGER.info("Received result: {} in {}ms", result, System.currentTimeMillis() - start);

        sleep(1000);
      }
      catch (RemoteMethodException e)
      {
        LOGGER.error("An error occurred invoking remote method.", e);
      }
    }
  }

  /**
   * Sleeps the calling thread for the specified number of <code>millis</code>.
   */
  private static void sleep(long millis)
  {
    try
    {
      Thread.sleep(millis);
    }
    catch (InterruptedException e)
    {
      //ignore.
    }
  }
}
